/* freeircd send.c
 *
 * Iniciado em 05/10/2006 (Movido de commands.c)
 */
#define _GNU_SOURCE

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

#include "misc.h"
#include "types.h"
#include "getinfo.h"

#include "debug.h"

extern void write_sock(CLIENTS *, char *, ...);
extern void write_sock_already_form(CLIENTS *, char *);

void send_to_all_in_chan(CLIENTS *client, char *chan, char *str, ...)
{
        char *formated=NULL;
        struct user_chans_list *chan_lst;
        va_list ap;

        va_start(ap, str);
        vasprintf(&formated,str,ap);
        va_end(ap);

        chan_lst=get_chan_from_user_list(client->chans,chan);

        if (chan_lst != NULL)
        {
                struct chan_users_list *usrs_lst=chan_lst->chan->users;

                if (chan_lst->secret)
                {
                        free(formated);
                        return;
                }

                while (usrs_lst != NULL)
                {
                        if (!compic(usrs_lst->user->nick,client->nick))
                                write_sock_already_form(usrs_lst->user,formated);

                        usrs_lst=usrs_lst->next;
                }
        }

        ndb_free(formated);
}

void send_to_all_in_chan_already_form(CLIENTS *client, char *chan, char *formated)
{
        struct user_chans_list *chan_lst;

        chan_lst=get_chan_from_user_list(client->chans,chan);

        if (chan_lst != NULL)
        {
                struct chan_users_list *usrs_lst=chan_lst->chan->users;

                if (chan_lst->secret)
                        return;

                while (usrs_lst != NULL)
                {
                        if (!compic(usrs_lst->user->nick,client->nick))
                                write_sock_already_form(usrs_lst->user,formated);

                        usrs_lst=usrs_lst->next;
                }
        }

}

void send_to_all(CLIENTS *client, char *str, ...)
{
        char *formated=NULL;
        struct user_chans_list *chan_lst=client->chans;
        va_list ap;

        va_start(ap, str);
        vasprintf(&formated,str,ap);
        va_end(ap);

        while (chan_lst != NULL)
        {
                send_to_all_in_chan_already_form(client,chan_lst->chan->name,formated);

                chan_lst=chan_lst->next;
        }

        ndb_free(formated);
}
